import openai
from django.conf import settings
from typing import List, Dict
import json


class AgentChatService:
    """智能体聊天服务"""
    
    def __init__(self, agent):
        self.agent = agent
        self.client = openai.OpenAI(
            api_key=getattr(settings, 'OPENAI_API_KEY', 'your-api-key'),
            base_url=getattr(settings, 'OPENAI_API_BASE', 'https://api.openai.com/v1')
        )
    
    def build_messages(self, conversation, new_message: str) -> List[Dict[str, str]]:
        """构建对话消息列表"""
        messages = []
        
        # 系统提示词
        system_prompt = self.agent.system_prompt
        if system_prompt:
            messages.append({
                "role": "system",
                "content": system_prompt
            })
        
        # 历史对话（取最近的10条消息避免超出token限制）
        recent_messages = conversation.messages.order_by('-created_at')[:10]
        for msg in reversed(recent_messages):
            messages.append({
                "role": msg.role,
                "content": msg.content
            })
        
        # 新消息
        messages.append({
            "role": "user",
            "content": new_message
        })
        
        return messages
    
    def generate_response(self, conversation, message: str) -> str:
        """生成AI响应"""
        try:
            messages = self.build_messages(conversation, message)
            
            # 调用OpenAI API
            response = self.client.chat.completions.create(
                model=self.agent.model_name,
                messages=messages,
                temperature=self.agent.temperature,
                max_tokens=self.agent.max_tokens
            )
            
            ai_response = response.choices[0].message.content.strip()
            return ai_response
            
        except openai.OpenAIError as e:
            return f"抱歉，AI服务暂时不可用: {str(e)}"
        except Exception as e:
            return f"发生错误: {str(e)}"
    
    def generate_title(self, first_message: str) -> str:
        """为对话生成标题"""
        try:
            response = self.client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {
                        "role": "system",
                        "content": "请为以下对话生成一个简短的标题（不超过30个字符）："
                    },
                    {
                        "role": "user", 
                        "content": first_message
                    }
                ],
                temperature=0.5,
                max_tokens=50
            )
            title = response.choices[0].message.content.strip()
            return title[:30]  # 确保不超过30个字符
        except:
            # 如果生成失败，使用消息的前30个字符作为标题
            return first_message[:30] + "..." if len(first_message) > 30 else first_message


class MockChatService:
    """模拟聊天服务（用于测试或无API key时）"""
    
    def __init__(self, agent):
        self.agent = agent
    
    def generate_response(self, conversation, message: str) -> str:
        """生成模拟响应"""
        responses = [
            f"这是一个来自 {self.agent.name} 的回复。您说: {message}",
            f"作为 {self.agent.name}，我理解您的问题。让我来帮助您。",
            f"感谢您使用 {self.agent.name}！我正在处理您的请求。",
            f"基于我的知识，我认为您提到的 '{message[:20]}...' 是一个有趣的话题。",
            f"我是 {self.agent.name}，很高兴为您服务。关于您的问题，我建议..."
        ]
        
        import random
        return random.choice(responses)
    
    def generate_title(self, first_message: str) -> str:
        """生成模拟标题"""
        return first_message[:30] + "..." if len(first_message) > 30 else first_message


def get_chat_service(agent):
    """获取聊天服务实例"""
    # 检查是否配置了OpenAI API Key
    api_key = getattr(settings, 'OPENAI_API_KEY', None)
    if api_key and api_key != 'your-openai-api-key':
        return AgentChatService(agent)
    else:
        return MockChatService(agent)